

import React, { useEffect, useRef, useState } from "react";
import styles from './PasswordLogin.module.css';
import { Close } from '@nutui/icons-react';
import { ArrowDown, ClosedEye, EyeO } from '@react-vant/icons';
import {Notify, Button, Input, Form, Picker, Space, } from 'react-vant';
import { Radio, Dialog } from '@nutui/nutui-react'
import { useLocation, useNavigate } from "react-router-dom";
import { http } from '../../utils'
import { useDispatch } from "react-redux";
import { putUserMessage } from "../../redux2/modules/cart";
const PhoneColumns = [
    { text: '86 🇨🇳', value: '86' },
    { text: '87 🇺🇸', value: '87' },
    { text: '88 🏳️‍🌈', value: '88' },
    { text: '89 🏳️‍⚧️', value: '89' },
    { text: '90 🇴🇲', value: '90' },
    { text: '91 🇵🇪', value: '91' },
    { text: '92 🇩🇪', value: '92' },
];

const PasswordLogin = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch()
    const [form] = Form.useForm(); // 创建 form 实例
    const [agreementBool, setAgreementBool] = useState(false)
    const [isAgreementDialog, setIsAgreementDialog] = useState(false)
    const [isInputPass, setIsInputPass] = useState(false)
    const createRef = useRef(false)
    const checkPhoneInput = (_, value) => {
        // 确保 value 存在且包含 prefix 和 value 属性
        if (!value || !value.prefix || !value.value) {
            return Promise.reject(new Error('请填写完整的手机号信息！'));
        }

        // 中国大陆手机号正则表达式
        const chinaMobileRegex = /^1[3-9]\d{9}$/;

        // 检查手机号格式
        if (!chinaMobileRegex.test(value.value)) {
            return Promise.reject(new Error('手机号格式错误！'));
        }

        // 如果所有校验通过
        return Promise.resolve();
    };

    const checkRulesCodeInput = (_, value) => {

        if (!value) {
            return Promise.reject(new Error('请填写用户密码信息！'));
        }
        // 如果所有校验通过
        return Promise.resolve();
    }

    const onFinish = (values) => {
        if (!agreementBool) {
            setIsAgreementDialog(true)
        } else {
            onSubLogin()
        }
        console.log(form.getFieldValue('phone'));
    };

    const onSubLogin = async()=>{
        let res = await http.post('/main/passwordLogin',{
            phone:form.getFieldValue('phone').value,
            password:form.getFieldValue('password')
        })
        
        if(res.code==200){
            navigate('/outlet/MySelf')
            localStorage.setItem('accessToken', res.data.accessToken);
            localStorage.setItem('refreshToken', res.data.refreshToken);
            dispatch(putUserMessage({phone:form.getFieldValue('phone').value}))
        }else{
            Notify.show({ type: 'danger', message: res.message })
        }
    }

    return (
        <div className={styles.code_out_box}>
            <div className={styles.code_close_box}><Close size='20' /></div>
            <div className={styles.code_title_box}>
                <h2 style={{ fontSize: '0.32rem' }}>密码登录</h2>
            </div>
            <div className={styles.code_form_box}>
                <Form
                    form={form}
                    onFinish={onFinish}
                    initialValues={{ phone: { prefix: '86', value: '' }, rulesCode: '' }}
                    footer={
                        <div style={{ margin: '30px 16px 0', }}>
                            <Button
                                round
                                nativeType='submit'
                                type='primary'
                                block
                                color={'linear-gradient(to right, #ff9600 , #fe4801)'}
                            >
                                登录
                            </Button>
                            <p style={{ color: "red", textAlign: 'center', marginTop: "0.2rem" }} onClick={() => navigate('/LoginCode')}>免密码登录</p>
                        </div>
                    }
                >
                    <Form.Item
                        style={{ minHeight: "0.8rem" }}
                        name='phone'
                        rules={[{ required: true }, { validator: checkPhoneInput }]}
                    >
                        <Picker
                            popup
                            placeholder={false}
                            columns={PhoneColumns}
                            onConfirm={(prefix) => {
                                form.setFieldsValue({
                                    phone: {
                                        ...form.getFieldValue('phone'),
                                        prefix,
                                    },
                                });
                            }}
                            value={form.getFieldValue('phone')?.prefix || '86'}
                        >
                            {(_, selectRow, actions) => (
                                <Space>
                                    <Space align="center" onClick={() => actions.open()}>
                                        <div style={{ fontSize: "0.22rem" }}>+{form.getFieldValue('phone')?.prefix || '86'}</div>
                                        <ArrowDown style={{ display: 'block' }} />
                                    </Space>
                                    <Input
                                        style={{ fontSize: '0.22rem' }}
                                        placeholder={'请输入手机号'}
                                        onChange={(value) => {
                                            form.setFieldsValue({
                                                phone: {
                                                    ...form.getFieldValue('phone'),
                                                    value,
                                                },
                                            });
                                        }}
                                        value={form.getFieldValue('phone')?.value || ''}
                                    />
                                </Space>
                            )}
                        </Picker>
                    </Form.Item>
                    <Form.Item
                        name='password'
                        style={{ minHeight: "0.8rem" }}
                        rules={[{ required: true }, { validator: checkRulesCodeInput }]}
                    >
                        <Input
                            type={isInputPass ? 'text' : 'password'}
                            suffix={
                                <div style={{ display: 'flex', alignItems: "center" }}>
                                    {
                                        isInputPass ?
                                            <EyeO onClick={() => setIsInputPass(!isInputPass)} />
                                            :
                                            <ClosedEye onClick={() => setIsInputPass(!isInputPass)} />
                                    }
                                    <span
                                        className={styles.font_color}
                                        style={{ fontSize: '0.14rem', marginLeft: '0.15rem' }}
                                    >
                                        找回密码
                                    </span>
                                </div>
                            }
                            placeholder="请输入密码"
                        />
                    </Form.Item>
                    <Form.Item >
                        <Radio
                            name="agreement"
                            onClick={() => { setAgreementBool(!agreementBool) }}
                            checked={agreementBool}
                        >
                            <p style={{ fontSize: "0.14rem" }}>我已阅读并同意签署
                                <span style={{ color: "red", fontSize: "0.14rem" }}>小五用户协议</span>和
                                <span style={{ color: "red", fontSize: "0.14rem" }}>小五隐私政策</span>
                            </p>
                        </Radio>
                    </Form.Item>
                </Form>
            </div>
            <Dialog
                title="是否同意小五协议"
                visible={isAgreementDialog}
                onConfirm={() => {
                    setIsAgreementDialog(false)
                    setAgreementBool(true)
                    onSubLogin()
                }}
                onCancel={() => setIsAgreementDialog(false)}
            ></Dialog>
        </div>
    );
};

export default PasswordLogin;